package com.yourbatis.interpreter;

import java.util.HashMap;
import java.util.Map;

public class Scope {
    public Scope getParent() {
        return parent;
    }

    private final Scope parent;  // 父作用域(用于实现嵌套)
    private final Map<String, Object> variables = new HashMap<>();
    private final Map<String, Class<?>> types = new HashMap<>();

    public Scope(Scope parent) {
        this.parent = parent;
    }

    // 变量定义
    public void define(String name, Object value) {
        if (variables.containsKey(name)) {
            throw new RuntimeException("变量已存在: " + name);
        }
        variables.put(name, value);
        if(value != null){
            types.put(name, value.getClass());
        }
    }

    // 变量赋值
    public void assign(String name, Object value) {
        if (variables.containsKey(name)) {
            // 类型检查
            if (!types.get(name).isInstance(value)) {
                throw new RuntimeException("Type mismatch for variable " + name);
            }
            variables.put(name, value);
        } else if (parent != null) {
            // 在父作用域中查找
            parent.assign(name, value);
        } else {
            throw new RuntimeException("Undefined variable: " + name);
        }
    }

    // 变量查找
    public Object get(String name) {
        if (variables.containsKey(name)) {
            return variables.get(name);
        }
        if (parent != null) {
            return parent.get(name);
        }
        throw new RuntimeException("Undefined variable: " + name);
    }

    // 检查变量是否存在
    public boolean contains(String name) {
        if (variables.containsKey(name)) {
            return true;
        }
        return parent != null && parent.contains(name);
    }

    public  void init(Map map){
        variables.putAll(map);
    }
}
